from fastapi import APIRouter, Depends, HTTPException, File, UploadFile,Form
from services.ocr_service import OCRService
from services.common_service import get_ocr_service,save_uploaded_file
from models.request import OCRRequest, OCRResponse
from typing import List, Optional
from config import settings
import base64
import os
import uuid
from datetime import datetime
from pathlib import Path

router = APIRouter(prefix="/ocr", tags=["OCR服务"])

# 文件存储目录（可从配置中读取）
STORAGE_DIR = settings.FILE_STORAGE_DIR if hasattr(settings, 'FILE_STORAGE_DIR') else "uploads"
Path(STORAGE_DIR).mkdir(parents=True, exist_ok=True)



@router.post("/analyze", response_model=OCRResponse)
async def analyze_document(
    query_keys: List[str] = Form(...),  # 拆分为表单字段
    use_orientation: bool = Form(False),
    use_unwarping: bool = Form(False),
    file: UploadFile = File(...),
    service: OCRService = Depends(get_ocr_service)
):
    
    print(query_keys)
    """文档图像分析与问答接口（支持文件持久化存储）"""
    try:
        # 保存上传文件
        saved_file_path = save_uploaded_file(file)
        print(saved_file_path)
        
        # 调用服务层处理文件
        result = service.process_document(
            file_path=saved_file_path,
            query_keys=query_keys,
            use_orientation=use_orientation,
            use_unwarping=use_unwarping
        )
        
        
        return OCRResponse(result=result)
    
    except RuntimeError as e:
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        # 发生异常时删除已保存的文件（可选）
        if 'saved_file_path' in locals():
            try:
                os.remove(saved_file_path)
            except:
                pass
        raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")